package com.oswift.cms.web.reception;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.oswift.cms.entity.MemberBean;
import com.oswift.cms.entity.MessageBean;
import com.oswift.cms.entity.reception.Announce;
import com.oswift.cms.entity.reception.Article;
import com.oswift.cms.entity.reception.Comment;
import com.oswift.cms.entity.reception.DataList;
import com.oswift.cms.entity.reception.Download;
import com.oswift.cms.entity.reception.FriendSite;
import com.oswift.cms.entity.reception.GuestBook;
import com.oswift.cms.entity.reception.Member;
import com.oswift.cms.entity.reception.MemberLoginInfo;
import com.oswift.cms.entity.reception.Pic;
import com.oswift.cms.entity.reception.WebConfig;
import com.oswift.cms.utils.Field;
import com.oswift.cms.utils.PageCode;
import com.oswift.cms.utils.ReceptionConstant;
import com.oswift.cms.utils.Field.CommentField;
import com.oswift.cms.utils.Field.TableName;
import com.oswift.utils.cache.ResourceManager;
import com.oswift.utils.common.DeviceUtils;
import com.oswift.utils.common.HtmlUtils;
import com.oswift.utils.common.IpUtil;
import com.oswift.utils.common.RegexUtils;
import com.oswift.utils.common.StringUtil;
import com.oswift.utils.common.TimeUtil;
import com.oswift.utils.exception.PlatException;

@Controller
@RequestMapping("/ajax")
public class RAjaxAction extends BaseAction
{
    /**
     * 日志实例
     */
    private static Logger log = LoggerFactory.getLogger(RAjaxAction.class);

    /**
     *
     * 获取栏目的ajax
     *
     * @author zhuou
     * @param contentType
     *            类型：all,one-level,fixed-all,fixed-one
     */
    @RequestMapping(value = "/channel")
    @ResponseBody
    public Object getChannelAjax(HttpServletRequest request)
    {
        int channelId = -1;
        MessageBean messBean = new MessageBean();

        // 获取参数
        String id = request.getParameter("id");
        String contentType = request.getParameter("contentType");

        if (StringUtil.isEmpty(contentType))
        {
            messBean.setCode(PageCode.PARAMETER_ISNOT_EMPTY);
            messBean.setContent(ResourceManager
                    .getValue(PageCode.PARAMETER_ISNOT_EMPTY));
            return messBean;
        }
        try
        {
            // 如果是查询指定栏目及其所有父栏目和所有子栏目或者查询指定栏目，则判断id是否有值
            if (ReceptionConstant.ContentType.CHANNEL_FIXED_ALL
                    .equalsIgnoreCase(contentType)
                    || ReceptionConstant.ContentType.CHANNEL_FIXED_ONE
                            .equalsIgnoreCase(contentType))
            {
                if (StringUtil.isEmpty(id))
                {
                    messBean.setCode(PageCode.PARAMETER_ISNOT_EMPTY);
                    messBean.setContent(ResourceManager
                            .getValue(PageCode.PARAMETER_ISNOT_EMPTY));
                    return messBean;
                }
                channelId = Integer.valueOf(id);
            }

            int companyId = this.getWebConfig(request).getCompanyId();

            Object obj = receptionService.getChannel(companyId, channelId,
                    contentType);
            messBean.setCode(PageCode.COMMON_SUCCESS);
            messBean.setObjContent(obj);
        }
        catch (Exception e)
        {
            log.error("The getChannelAjax of ajax request exception.", e);
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean
                    .setContent(ResourceManager.getValue(PageCode.COMMON_ERROR));
        }
        return messBean;
    }

    /**
     *
     * 获取内容的ajax
     *
     * @author zhuou
     */
    @RequestMapping(value = "/content")
    @ResponseBody
    public Object getContentAjax(HttpServletRequest request)
    {
        MessageBean messBean = new MessageBean();

        String forum = request.getParameter("forum");
        if (StringUtil.isEmpty(forum))
        {
            messBean.setCode(PageCode.PARAMETER_ISNOT_EMPTY);
            messBean.setContent(ResourceManager
                    .getValue(PageCode.PARAMETER_ISNOT_EMPTY));
            return messBean;
        }
        // 获取频道表名称
        forum = getTableName(forum);
        if (StringUtil.isEmpty(forum))
        {
            messBean.setCode(PageCode.PARAMETER_TYPE_ERROR);
            messBean.setContent(ResourceManager
                    .getValue(PageCode.PARAMETER_TYPE_ERROR)
                    + ",forum参数错误！");
            return messBean;
        }

        try
        {
            // 内容类型
            String contentType = request.getParameter("contentType");
            // 栏目id
            int channelId = -1;
            String id = request.getParameter("id");
            if (!StringUtil.isEmpty(id))
            {
                channelId = Integer.valueOf(id);
            }
            // 如果为-1则表示没有分页，如果大于0则表示目前第几页
            int iNowPage = -1;
            String nowPage = request.getParameter("nowPage");
            if (!StringUtil.isEmpty(nowPage))
            {
                iNowPage = Integer.valueOf(nowPage);
            }
            // 每页几条数据
            int iPageNum = this.pageRecordNum;
            String pageNum = request.getParameter("pageNum");
            if (!StringUtil.isEmpty(pageNum))
            {
                iPageNum = Integer.valueOf(pageNum);
            }
            // 获取站点和公司id信息
            WebConfig webConfig = this.getWebConfig(request);
            int companyId = webConfig.getCompanyId();

            DataList data = receptionService.contentList(companyId, channelId,
                    contentType, iPageNum, iNowPage, forum);
            messBean.setCode(PageCode.COMMON_SUCCESS);
            messBean.setObjContent(data);
        }
        catch (Exception e)
        {
            log.error("The getContentAjax of ajax request exception.", e);
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean
                    .setContent(ResourceManager.getValue(PageCode.COMMON_ERROR));
        }
        return messBean;
    }

    /**
     *
     * 获取评论
     *
     * @contentType new,recommend
     * @author zhuou
     */
    @RequestMapping(value = "/comment")
    @ResponseBody
    public Object getCommentAjax(HttpServletRequest request)
    {
        // 消息对象
        MessageBean messBean = new MessageBean();

        String id = request.getParameter("id");
        String contentType = request.getParameter("contentType");
        String nowPage = request.getParameter("nowPage");
        String topNum = request.getParameter("topNum");
        if (StringUtil.isEmpty(id))
        {
            messBean.setCode(PageCode.PARAMETER_ISNOT_EMPTY);
            messBean.setContent(ResourceManager
                    .getValue(PageCode.PARAMETER_ISNOT_EMPTY));
            return messBean;
        }

        try
        {
            // 内容id
            long contentId = -1L;
            if (!StringUtil.isBlank(id))
            {
                contentId = Long.valueOf(id);
            }
            // 公司id
            int companyId = this.getWebConfig(request).getCompanyId();
            // 如果nowPage为空，则没有分页要求
            int iNowPage = -1;
            if (!StringUtil.isBlank(nowPage))
            {
                iNowPage = Integer.valueOf(nowPage);
            }

            int iTopNum = pageRecordNum;
            // 显示几条数据
            if (!StringUtil.isBlank(topNum))
            {
                iTopNum = Integer.valueOf(topNum);
            }

            Object obj = receptionService.getCommentList(companyId, contentId,
                    contentType, iTopNum, iNowPage);
            messBean.setCode(PageCode.COMMON_SUCCESS);
            messBean.setObjContent(obj);
        }
        catch (Exception e)
        {
            log.error("The getCommentAjax of ajax request exception.", e);
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean
                    .setContent(ResourceManager.getValue(PageCode.COMMON_ERROR));
        }
        return messBean;
    }

    /**
     *
     * 获取内容详情
     *
     * @author zhuou
     */
    @RequestMapping(value = "/detail")
    @ResponseBody
    public Object getDetailAjax(HttpServletRequest request)
    {
        MessageBean messBean = new MessageBean();

        String forum = request.getParameter("forum");
        // 栏目id或者是详情内容id
        String id = request.getParameter("id");
        // 0有没有上一条下一条 1有上一条下一条
        String isRelation = request.getParameter("isRelation");

        if (StringUtil.isEmpty(forum) || StringUtil.isEmpty(id))
        {
            messBean.setCode(PageCode.PARAMETER_ISNOT_EMPTY);
            messBean.setContent(ResourceManager
                    .getValue(PageCode.PARAMETER_ISNOT_EMPTY));
            return messBean;
        }

        try
        {
            boolean isPage = false;
            if ("1".equals(isRelation))
            {
                isPage = true;
            }
            if (Field.TableName.ARTICLE.equals(forum))
            {
                Article article = receptionService.getArticleDetail(Long
                        .valueOf(id), 1, isPage, 1);
                messBean.setObjContent(article);
            }
            else if (Field.TableName.ANNOUNCE.equals(forum))
            {
                Announce announce = receptionService.getAnnounceDetail(Long
                        .valueOf(id), isPage);
                messBean.setObjContent(announce);
            }
            else if (Field.TableName.DOWNLOAD.equals(forum))
            {
                Download download = receptionService.getDownloadDetail(Long
                        .valueOf(id), isPage);
                messBean.setObjContent(download);
            }
            else if (Field.TableName.PICURL.equals(forum))
            {
                Pic pic = receptionService.getPicDetail(Long.valueOf(id),
                        isPage);
                messBean.setObjContent(pic);
            }
            else if (Field.TableName.GUESTBOOK.equals(forum))
            {
                GuestBook guestBook = receptionService.getGuestBookDetail(Long
                        .valueOf(id), isPage);
                messBean.setObjContent(guestBook);
            }
            else if (Field.TableName.FRIENDSITE.equals(forum))
            {
                FriendSite friendSite = receptionService.getFriendSiteDetail(
                        Long.valueOf(id), false);
                messBean.setObjContent(friendSite);
            }
            else
            {
                messBean.setObjContent(null);
            }
            messBean.setCode(PageCode.COMMON_SUCCESS);
        }
        catch (PlatException e)
        {
            log.error("The getDetailAjax of ajax request exception.", e);
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean
                    .setContent(ResourceManager.getValue(PageCode.COMMON_ERROR));
        }
        return messBean;
    }

    /**
     *
     * 新增留言或者用户反馈
     *
     * @author zhuou
     */
    @RequestMapping(value = "/addFeedback")
    @ResponseBody
    public Object addFeedback(HttpServletRequest request)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            String guestEmail = StringUtil.trim(request
                    .getParameter("guestEmail"));
            String phoneNumber = StringUtil.trim(request
                    .getParameter("phoneNumber"));
            String guestOicq = StringUtil.trim(request
                    .getParameter("guestOicq"));
            String guestIsPrivate = StringUtil.trim((request
                    .getParameter("guestIsPrivate")));
            String guestContent = StringUtil.trim(request
                    .getParameter("guestContent"));
            String channelId = StringUtil.trim(request
                    .getParameter("channelId"));
            String title = StringUtil.trim(request.getParameter("title"), "");
            String status = StringUtil.trim(request.getParameter("status"));
            String validateCode = StringUtil.trim((request
                    .getParameter("validateCode")));
            if (StringUtil.isBlank(guestContent))
            {
                messBean.setCode(PageCode.TEXTFIELD_ISNOT_EMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.TEXTFIELD_ISNOT_EMPTY));
                return messBean;
            }
            if (null != validateCode)
            {
                if (StringUtil.isEmpty(validateCode))
                {
                    messBean.setCode(PageCode.VALIDATECODE_EMPTY);
                    messBean.setContent(ResourceManager
                            .getValue(PageCode.VALIDATECODE_EMPTY));
                    return messBean;
                }
                Object oValidataCode = request.getSession().getAttribute(
                        "validataCode");
                if (null == oValidataCode)
                {
                    messBean.setCode(PageCode.VALIDATECODE_OVERTIME);
                    messBean.setContent(ResourceManager
                            .getValue(PageCode.VALIDATECODE_OVERTIME));
                    return messBean;
                }

                if (!validateCode.equalsIgnoreCase(String
                        .valueOf(oValidataCode)))
                {
                    messBean.setCode(PageCode.VALIDATECODE_ERROR);
                    messBean.setContent(ResourceManager
                            .getValue(PageCode.VALIDATECODE_ERROR));
                    return messBean;
                }
            }
            int iChannelId = 0;
            if (!StringUtil.isBlank(channelId))
            {
                iChannelId = Integer.valueOf(channelId);
            }
            // 默认会员信息
            long userId = CommentField.DEFAULT_USERID;
            String userName = CommentField.DEFAULT_USERNAME;

            // 获取会员信息
            Object obj = request.getSession()
                    .getAttribute(Field.MEMBER_SESSION);
            if (null != obj)
            {
                Member member = (Member) obj;
                userId = member.getUserId();
                userName = member.getUserName();
            }

            int companyId = this.getWebConfig(request).getCompanyId();
            GuestBook bean = new GuestBook();
            bean.setChannelId(iChannelId);
            bean.setGuestEmail(guestEmail);
            bean.setPhoneNumber(phoneNumber);
            bean.setGuestOicq(guestOicq);
            bean.setUserName(userName);
            bean.setUserId(userId);
            bean.setInputer(userName);
            if (Field.TRUE.equals(guestIsPrivate))
            {
                bean.setGuestIsPrivate(true);
            }
            else
            {
                bean.setGuestIsPrivate(false);
            }
            bean.setGuestContent(guestContent);
            bean.setTitle(title);
            int iStatus = Field.Status.PENDING_AUDIT;
            if (!StringUtil.isBlank(status))
            {
                iStatus = Integer.valueOf(status);
            }
            boolean isSuccess = receptionService.addGuestbook(bean, companyId,
                    iStatus);
            if (isSuccess)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.GUESTBOOK_ADD_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.GUESTBOOK_ADD_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.GUESTBOOK_ADD_FAIL));
            }
        }
        catch (PlatException e)
        {
            log.error("The addFeedback of ajax request exception.", e);
            messBean.setCode(PageCode.GUESTBOOK_ADD_FAIL);
            messBean.setContent(ResourceManager
                    .getValue(PageCode.GUESTBOOK_ADD_FAIL));
        }
        return messBean;
    }

    /**
     *
     * 前台新增文章
     *
     * @author zhuou
     */
    @RequestMapping(value = "/addArticle")
    @ResponseBody
    public Object addArticle(HttpServletRequest request)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            String titlePrefix = StringUtil.trim(request
                    .getParameter("titlePrefix"));
            String titleIntact = StringUtil.trim(request
                    .getParameter("titleIntact"));
            String title = StringUtil.trim(request.getParameter("title"));
            String subheading = StringUtil.trim(request
                    .getParameter("subheading"));
            String marqueeImg = StringUtil.trim(request
                    .getParameter("marqueeImg"));
            String keyWord = StringUtil.trim(request.getParameter("keyWord"));
            String intro = StringUtil.trim(request.getParameter("intro"));
            String focusImg = StringUtil.trim(request.getParameter("focusImg"));
            String defaultPicUrl = StringUtil.trim(request
                    .getParameter("defaultPicUrl"));
            String content = StringUtil.trim(request.getParameter("content"));
            String channelId = StringUtil.trim(request
                    .getParameter("channelId"));
            String bigNewsImg = StringUtil.trim(request
                    .getParameter("bigNewsImg"));
            String status = StringUtil.trim(request.getParameter("status"));
            if (StringUtil.isBlank(title) || StringUtil.isBlank(content))
            {
                messBean.setCode(PageCode.TEXTFIELD_ISNOT_EMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.TEXTFIELD_ISNOT_EMPTY));
                return messBean;
            }

            String userName = CommentField.DEFAULT_USERNAME;
            // 获取会员信息
            Object obj = request.getSession()
                    .getAttribute(Field.MEMBER_SESSION);
            if (null != obj)
            {
                Member member = (Member) obj;
                userName = member.getUserName();
            }
            // 获取公司id
            int companyId = this.getWebConfig(request).getCompanyId();
            int iChannelId = 0;
            if (!StringUtil.isBlank(channelId))
            {
                iChannelId = Integer.valueOf(channelId);
            }
            // 获取内容中有多少张图片
            List<String> imgList = HtmlUtils.getImgSrcFromHtml(content);

            Article bean = new Article();
            bean.setAuthor(userName);
            bean.setBigNewsImg(bigNewsImg);
            bean.setChannelId(iChannelId);
            bean.setCompanyId(companyId);
            bean.setContent(content);
            if (null != imgList && !imgList.isEmpty())
            {
                bean.setContentImgNum(imgList.size());
            }
            else
            {
                bean.setContentImgNum(0);
            }
            bean.setCreateTime(new Date());
            // 将等于空的赋值为null，便于查询
            if (StringUtil.isBlank(defaultPicUrl))
            {
                bean.setDefaultPicUrl(null);
            }
            else
            {
                bean.setDefaultPicUrl(defaultPicUrl);
            }
            bean.setFocusImg(focusImg);
            bean.setInputer(userName);
            bean.setIntro(intro);
            bean.setKeyWord(keyWord);
            bean.setMarqueeImg(marqueeImg);
            bean.setSubheading(subheading);
            bean.setTitle(title);
            if (null == titleIntact)
            {
                bean.setTitleIntact("");
            }
            else
            {
                bean.setTitleIntact(titleIntact);
            }
            bean.setTitlePrefix(titlePrefix);

            int iStatus = Field.Status.PENDING_AUDIT;
            if (!StringUtil.isBlank(status))
            {
                iStatus = Integer.valueOf(status);
            }
            boolean isSuccess = receptionService.addArticle(bean, companyId,
                    iStatus);
            if (isSuccess)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.ARTICLE_ADD_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.ARTICLE_ADD_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.ARTICLE_ADD_FAIL));
            }
        }
        catch (PlatException e)
        {
            log.error("The addArticle of ajax request exception.", e);
            messBean.setCode(PageCode.ARTICLE_ADD_FAIL);
            messBean.setContent(ResourceManager
                    .getValue(PageCode.ARTICLE_ADD_FAIL));
        }
        return messBean;
    }

    /**
     *
     * 新增评论
     *
     * @author zhuou
     */
    @RequestMapping(value = "/addComment")
    @ResponseBody
    public Object addComment(HttpServletRequest request)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            String commonModelId = request.getParameter("commonModelId");
            String commentTitle = request.getParameter("commentTitle");
            String commentContent = request.getParameter("commentContent");
            // 是否公开
            String isPrivate = request.getParameter("isPrivate");
            String commentType = request.getParameter("commentType");
            if (StringUtil.isBlank(commonModelId))
            {
                messBean.setCode(PageCode.GET_WEBPARAM_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                return messBean;
            }
            if (StringUtil.isBlank(commentContent))
            {
                messBean.setCode(PageCode.COMMENTCONTENT_ISEMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.COMMENTCONTENT_ISEMPTY));
                return messBean;
            }

            // 获取评论人Ip
            String ip = IpUtil.getRequestIP(request);
            // 获取公司id
            WebConfig webConfig = this.getWebConfig(request);
            int companyId = webConfig.getCompanyId();

            // 默认会员信息
            long userId = CommentField.DEFAULT_USERID;
            String userName = CommentField.DEFAULT_USERNAME;

            // 获取会员信息
            Object obj = request.getSession()
                    .getAttribute(Field.MEMBER_SESSION);
            if (null != obj)
            {
                Member member = (Member) obj;
                userId = member.getUserId();
                userName = member.getUserName();
            }

            int iCommentType = CommentField.PC;
            // 如果commentType不为空，则从此参数中获取
            if (!StringUtil.isBlank(commentType))
            {
                if (String.valueOf(CommentField.PC).equals(commentType))
                {
                    iCommentType = CommentField.PC;
                }
                else if (String.valueOf(CommentField.PHONE).equals(commentType))
                {
                    iCommentType = CommentField.PHONE;
                }
                else
                {
                }
            }
            // 如果为空，则从request中判断是pc还是移动
            else
            {
                boolean isMobile = DeviceUtils.isMobileDevice(request);
                if (isMobile)
                {
                    iCommentType = CommentField.PHONE;
                }
                else
                {
                    iCommentType = CommentField.PC;
                }
            }

            // 判断评论是否公开（true表示不公开 false表示公开） 默认值为false
            boolean bIsPrivate = false;
            if (!StringUtil.isBlank(isPrivate))
            {
                if (Field.TRUE.equalsIgnoreCase(isPrivate))
                {
                    bIsPrivate = true;
                }
                else
                {
                    bIsPrivate = false;
                }
            }

            // TODO 过滤敏感字
            // TODO 评论积分

            Comment commentbean = new Comment();
            commentbean.setCompanyId(companyId);
            commentbean.setCommentContent(commentContent);
            commentbean.setCommentTitle(commentTitle);
            commentbean.setCommentType(iCommentType);
            commentbean.setCommonModelId(Long.valueOf(commonModelId));
            commentbean.setCreateTime(new Date());
            commentbean.setIp(ip);
            commentbean.setUserId(userId);
            commentbean.setUserName(userName);
            boolean isSuccess = receptionService.addComment(commentbean,
                    bIsPrivate);
            if (!isSuccess)
            {
                messBean.setCode(PageCode.ADD_COMMENT_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.ADD_COMMENT_FAIL));
            }
            else
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.ADD_COMMENT_SUCCESS));
                messBean.setObjContent(commentbean);
            }
        }
        catch (Exception e)
        {
            log.error("The addComment of ajax request exception.", e);
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean
                    .setContent(ResourceManager.getValue(PageCode.COMMON_ERROR));
        }
        return messBean;
    }

    /**
     *
     * 评论态度 Agree:1 Neutral:2 Oppose:3
     *
     * @author zhuou
     */
    @RequestMapping(value = "/commentAttitude")
    @ResponseBody
    public Object commentAttitude(HttpServletRequest request)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            String commentId = request.getParameter("id");
            String type = request.getParameter("type");
            if (StringUtil.isBlank(commentId))
            {
                messBean.setCode(PageCode.GET_WEBPARAM_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                return messBean;
            }

            boolean isSuccess = receptionService.commentAttitude(Long
                    .valueOf(commentId), type);
            if (isSuccess)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.COMMENTATTITUDE_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.COMMENTATTITUDE_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.COMMENTATTITUDE_FAIL));
            }
        }
        catch (Exception e)
        {
            log.error("The commentAttitude of ajax request exception.", e);
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean
                    .setContent(ResourceManager.getValue(PageCode.COMMON_ERROR));
        }
        return messBean;
    }

    /**
     *
     * 会员注册
     *
     * @author zhuou
     */
    @RequestMapping(value = "/memberRegister")
    @ResponseBody
    public Object memberRegister(HttpServletRequest request)
    {
        // 获取页面数据
        String groupId = request.getParameter("groupId");
        String userName = request.getParameter("userName");
        String userPassword = request.getParameter("userPassword");
        String userRePassword = request.getParameter("userRePassword");
        String question = request.getParameter("question");
        String answer = request.getParameter("answer");
        String trueName = request.getParameter("trueName");
        String email = request.getParameter("email");
        String officePhone = request.getParameter("officePhone");
        String mobile = request.getParameter("mobile");
        String homePhone = request.getParameter("homePhone");
        String qq = request.getParameter("qq");
        String birthday = request.getParameter("birthday");
        String cardType = request.getParameter("cardType");
        String nativePlace = request.getParameter("nativePlace");
        String nation = request.getParameter("nation");
        String sex = request.getParameter("sex");
        String marriage = request.getParameter("marriage");
        String education = request.getParameter("education");
        String graduateFrom = request.getParameter("graduateFrom");
        String interestsOfLife = request.getParameter("interestsOfLife");
        String interestsOfCulture = request.getParameter("interestsOfCulture");
        String interestsOfAmusement = request
                .getParameter("interestsOfAmusement");
        String interestsOfSport = request.getParameter("interestsOfSport");
        String interestsOfOther = request.getParameter("interestsOfOther");
        String income = request.getParameter("income");
        String family = request.getParameter("family");
        String company = request.getParameter("company");
        String department = request.getParameter("department");
        String position = request.getParameter("position");
        String companyAddress = request.getParameter("companyAddress");
        String province = request.getParameter("province");
        String city = request.getParameter("city");
        String district = request.getParameter("district");
        String zipCode = request.getParameter("zipCode");
        String address = request.getParameter("address");
        String faceHeight = request.getParameter("faceHeight");
        String faceWidth = request.getParameter("faceWidth");
        String homepage = request.getParameter("homepage");
        String idCard = request.getParameter("idCard");
        String userFace = request.getParameter("userFace");
        String attachment = request.getParameter("attachment");
        String validateCode = request.getParameter("validate");

        // 返回消息实体
        MessageBean messBean = new MessageBean();
        if (StringUtil.isBlank(userName))
        {
            messBean.setCode(PageCode.MEMBER_USERISEMPTY);
            messBean.setContent(ResourceManager
                    .getValue(PageCode.MEMBER_USERISEMPTY));
            return messBean;
        }
        if (StringUtil.isBlank(userPassword))
        {
            messBean.setCode(PageCode.MEMBER_PASSWORDISEMPTY);
            messBean.setContent(ResourceManager
                    .getValue(PageCode.MEMBER_PASSWORDISEMPTY));
            return messBean;
        }
        if (StringUtil.isBlank(userRePassword))
        {
            messBean.setCode(PageCode.MEMBER_REPASSWORDISEMPTY);
            messBean.setContent(ResourceManager
                    .getValue(PageCode.MEMBER_REPASSWORDISEMPTY));
            return messBean;
        }
        if (!userPassword.equals(userRePassword))
        {
            messBean.setCode(PageCode.MEMBER_PASSWORDTWOERROR);
            messBean.setContent(ResourceManager
                    .getValue(PageCode.MEMBER_PASSWORDTWOERROR));
            return messBean;
        }
        // 如果validateCode不为空，则要对验证码进行验证
        if (null != validateCode)
        {
            Object oValidataCode = request.getSession().getAttribute(
                    "validataCode");
            if (null == oValidataCode)
            {
                messBean.setCode(PageCode.VALIDATECODE_OVERTIME);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.VALIDATECODE_OVERTIME));
                return messBean;
            }

            if (!validateCode.equalsIgnoreCase(String.valueOf(oValidataCode)))
            {
                messBean.setCode(PageCode.VALIDATECODE_ERROR);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.VALIDATECODE_ERROR));
                return messBean;
            }
        }

        try
        {
            // 会员
            MemberBean memberBean = new MemberBean();
            memberBean.setAddress(StringUtil.trim(address));
            memberBean.setAnswer(StringUtil.trim(answer));
            memberBean.setAttachment(StringUtil.trim(attachment));
            if (null != birthday)
            {
                memberBean.setBirthday(TimeUtil.stringToDate(birthday,
                        TimeUtil.ISO_DATE_FORMAT));
            }
            if (!StringUtil.isBlank(cardType))
            {
                memberBean.setCardType(Integer.valueOf(cardType));
            }
            else
            {
                // 默认
                memberBean
                        .setCardType(ReceptionConstant.MemberConstant.CardType.IDCARD);
            }
            memberBean.setCity(StringUtil.trim(city));
            memberBean.setCompany(StringUtil.trim(company));
            memberBean.setCompanyAddress(StringUtil.trim(companyAddress));
            memberBean.setCreateTime(new Date());
            memberBean.setDepartment(StringUtil.trim(department));
            memberBean.setDistrict(StringUtil.trim(district));
            memberBean.setEducation(StringUtil.trim(education));
            memberBean.setEmail(StringUtil.trim(email));
            memberBean.setEnableResetPassword(true);
            if (!StringUtil.isBlank(faceHeight))
            {
                memberBean.setFaceHeight(Integer.valueOf(faceHeight));
            }
            if (!StringUtil.isBlank(faceWidth))
            {
                memberBean.setFaceWidth(Integer.valueOf(faceWidth));
            }
            memberBean.setFamily(StringUtil.trim(family));
            memberBean.setGraduateFrom(StringUtil.trim(graduateFrom));
            memberBean.setHomepage(StringUtil.trim(homepage));
            memberBean.setHomePhone(StringUtil.trim(homePhone));
            memberBean.setIdCard(StringUtil.trim(idCard));
            memberBean.setIncome(StringUtil.trim(income));
            memberBean.setInterestsOfAmusement(StringUtil
                    .trim(interestsOfAmusement));
            memberBean.setInterestsOfCulture(StringUtil
                    .trim(interestsOfCulture));
            memberBean.setInterestsOfLife(StringUtil.trim(interestsOfLife));
            memberBean.setInterestsOfOther(StringUtil.trim(interestsOfOther));
            memberBean.setInterestsOfSport(StringUtil.trim(interestsOfSport));
            if (!StringUtil.isBlank(marriage))
            {
                memberBean.setMarriage(Integer.valueOf(marriage));
            }
            else
            {
                memberBean
                        .setMarriage(ReceptionConstant.MemberConstant.Marriage.SECRET);
            }
            memberBean.setMobile(StringUtil.trim(mobile));
            memberBean.setNation(StringUtil.trim(nation));
            memberBean.setNativePlace(StringUtil.trim(nativePlace));
            memberBean.setOfficePhone(StringUtil.trim(officePhone));
            memberBean.setPosition(StringUtil.trim(position));
            memberBean.setProvince(StringUtil.trim(province));
            memberBean.setQq(StringUtil.trim(qq));
            memberBean.setQuestion(StringUtil.trim(question));
            memberBean.setRegTime(new Date());
            if (!StringUtil.isBlank(sex))
            {
                memberBean.setSex(Integer.valueOf(sex));
            }
            memberBean
                    .setStatus(ReceptionConstant.MemberConstant.Status.NORMAL);
            memberBean.setTrueName(trueName);
            memberBean.setUserFace(StringUtil.trim(userFace));
            memberBean.setUserName(StringUtil.trim(userName));
            memberBean.setUserPassword(userPassword);
            memberBean.setZipCode(StringUtil.trim(zipCode));

            // 获取站点和公司id信息
            WebConfig webConfig = this.getWebConfig(request);
            if (!StringUtil.isBlank(groupId))
            {
                memberBean.setGroupId(Integer.valueOf(groupId));
            }

            // 注册
            messBean = receptionService.memberRegister(memberBean, webConfig
                    .getCompanyId());
        }
        catch (PlatException e)
        {
            messBean.setCode(e.getExceptionCode());
            messBean.setContent(ResourceManager.getValue(e.getExceptionCode()));
            log.error("The method of memberRegister is error!", e);
        }
        catch (Exception e)
        {
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean.setContent(e.getMessage());
            log.error("The method of memberRegister is error!", e);
        }

        return messBean;
    }

    /**
     *
     * 广告点击数
     *
     * @author zhuou
     */
    @RequestMapping(value = "/clickAd")
    @ResponseBody
    public Object clickAd(HttpServletRequest request)
    {
        String id = request.getParameter("id");
        MessageBean messBean = new MessageBean();
        if (StringUtil.isEmpty(id))
        {
            messBean.setCode(PageCode.PARAMETER_ISNOT_EMPTY);
            messBean.setContent(ResourceManager
                    .getValue(PageCode.PARAMETER_ISNOT_EMPTY));
            return messBean;
        }

        try
        {
            boolean isSuccess = receptionService.addAdClicks(Integer
                    .valueOf(id));
            if (isSuccess)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.COMMON_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.ADD_ADCLICK_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.ADD_ADCLICK_FAIL));
            }
        }
        catch (Exception e)
        {
            log.error("The clickAd of ajax request exception.", e);
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean
                    .setContent(ResourceManager.getValue(PageCode.COMMON_ERROR));
        }
        return messBean;
    }

    /**
     *
     * 文章赞踩
     *
     * @author zhuou
     */
    @RequestMapping(value = "/clickApp")
    @ResponseBody
    public Object clickAppraise(HttpServletRequest request)
    {
        String id = request.getParameter("id");
        String type = request.getParameter("type");
        MessageBean messBean = new MessageBean();
        if (StringUtil.isEmpty(id) || StringUtil.isEmpty(type))
        {
            messBean.setCode(PageCode.PARAMETER_ISNOT_EMPTY);
            messBean.setContent(ResourceManager
                    .getValue(PageCode.PARAMETER_ISNOT_EMPTY));
            return messBean;
        }

        try
        {
            boolean isSuccess = receptionService.clickAppraise(
                    Long.valueOf(id), type);
            if (isSuccess)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.COMMON_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.CLICK_APPRAISE_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.CLICK_APPRAISE_FAIL));
            }
        }
        catch (Exception e)
        {
            log.error("The clickAppraise of ajax request exception.", e);
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean
                    .setContent(ResourceManager.getValue(PageCode.COMMON_ERROR));
        }
        return messBean;
    }

    /**
     *
     * 用户登录
     *
     * @author zhuou
     */
    @RequestMapping(value = "/login")
    @ResponseBody
    public Object login(HttpServletRequest request)
    {
        String userName = request.getParameter("userName");
        String userPassword = request.getParameter("userPassword");
        String validateCode = request.getParameter("validate");

        MessageBean messBean = new MessageBean();
        if (StringUtil.isBlank(userName))
        {
            messBean.setCode(PageCode.MEMBER_USERISEMPTY);
            messBean.setContent(ResourceManager
                    .getValue(PageCode.MEMBER_USERISEMPTY));
            return messBean;
        }
        if (StringUtil.isBlank(userPassword))
        {
            messBean.setCode(PageCode.MEMBER_PASSWORDISEMPTY);
            messBean.setContent(ResourceManager
                    .getValue(PageCode.MEMBER_PASSWORDISEMPTY));
            return messBean;
        }
        // 如果validateCode不为空，则要对验证码进行验证
        if (null != validateCode)
        {
            Object oValidataCode = request.getSession().getAttribute(
                    "validataCode");
            if (null == oValidataCode)
            {
                messBean.setCode(PageCode.VALIDATECODE_OVERTIME);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.VALIDATECODE_OVERTIME));
                return messBean;
            }

            if (!validateCode.equalsIgnoreCase(String.valueOf(oValidataCode)))
            {
                messBean.setCode(PageCode.VALIDATECODE_ERROR);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.VALIDATECODE_ERROR));
                return messBean;
            }
        }

        try
        {
            // 获取站点和公司id信息
            WebConfig webConfig = this.getWebConfig(request);
            String loginIp = IpUtil.getRequestIP(request);
            messBean = receptionService.memberLogin(webConfig.getCompanyId(),
                    userName, userPassword, loginIp);

            // 成功将用户信息存入session
            if (PageCode.COMMON_SUCCESS.equals(messBean.getCode()))
            {
                request.getSession().setAttribute(Field.MEMBER_SESSION,
                        messBean.getObjContent());
            }
        }
        catch (PlatException e)
        {
            messBean.setCode(e.getExceptionCode());
            messBean.setContent(ResourceManager.getValue(e.getExceptionCode()));
            log.error("The method of login is error!", e);
        }
        catch (Exception e)
        {
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean.setContent(e.getMessage());
            log.error("The method of login is error!", e);
        }
        return messBean;
    }

    /**
     *
     * 上传图片，并保存到磁盘上
     *
     * @author zhuou
     */
    @RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
    @ResponseBody
    public Object uploadImg(HttpServletRequest request)
    {
        MessageBean messBean = null;
        try
        {
            // 获取站点和公司id信息
            WebConfig webConfig = this.getWebConfig(request);
            messBean = receptionService.uploadImg(request, webConfig
                    .getCompanyId());
        }
        catch (Exception e)
        {
            messBean = new MessageBean();
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean.setContent(e.getMessage());
            log.error("The method of uploadImg is error!", e);
        }
        return messBean;
    }

    /**
     *
     * 删除上传的文件
     *
     * @author zhuou
     */
    @RequestMapping(value = "/delFile", method = RequestMethod.GET)
    @ResponseBody
    public Object delFile(HttpServletRequest request)
    {
        MessageBean messBean = null;
        try
        {
            String sId = request.getParameter("id");
            if (!RegexUtils.isNumber(sId))
            {
                messBean.setCode(PageCode.PARAMETER_ISNOT_EMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.PARAMETER_ISNOT_EMPTY));
                return messBean;
            }

            // 获取站点和公司id信息
            WebConfig webConfig = this.getWebConfig(request);
            messBean = receptionService.delFile(request, Long.parseLong(sId),
                    webConfig.getCompanyId());
        }
        catch (Exception e)
        {
            messBean = new MessageBean();
            messBean.setCode(PageCode.COMMON_ERROR);
            messBean.setContent(e.getMessage());
            log.error("The method of delFile is error!", e);
        }
        return messBean;
    }

    /**
     *
     * 用户退出
     *
     * @author zhuou
     */
    @RequestMapping(value = "/logout")
    @ResponseBody
    public Object logout(HttpServletRequest request)
    {
        if (null != request.getSession())
        {
            request.getSession().removeAttribute(Field.MEMBER_SESSION);
        }
        MessageBean messBean = new MessageBean();
        messBean.setCode(PageCode.COMMON_SUCCESS);
        messBean.setContent(ResourceManager.getValue(PageCode.COMMON_SUCCESS));
        return messBean;
    }

    /**
     *
     * ajax判断是否登录
     *
     * @author zhuou
     */
    @RequestMapping(value = "/isLogin")
    @ResponseBody
    public Object isLogin(HttpServletRequest request)
    {
        // 用户登录信息
        MemberLoginInfo memberLoginInfo = new MemberLoginInfo();

        HttpSession session = request.getSession();
        if (null == session
                || null == session.getAttribute(Field.MEMBER_SESSION))
        {
            return memberLoginInfo;
        }

        // 获取放在session里的用户信息
        Member member = (Member) session.getAttribute(Field.MEMBER_SESSION);
        memberLoginInfo.setLoginFlag(true);
        memberLoginInfo.setMember(member);

        return memberLoginInfo;
    }

    /**
     *
     * 获取文章频道表名称
     *
     * @author zhuou
     * @param forum
     *            板块名称
     * @return 文章频道表名称
     */
    private String getTableName(String forum)
    {
        forum = forum.toLowerCase();
        if (TableName.ARTICLE.toLowerCase().indexOf(forum) != -1)
        {
            return TableName.ARTICLE;
        }
        else if (TableName.ANNOUNCE.toLowerCase().indexOf(forum) != -1)
        {
            return TableName.ANNOUNCE;
        }
        else if (TableName.DOWNLOAD.toLowerCase().indexOf(forum) != -1)
        {
            return TableName.DOWNLOAD;
        }
        else if (TableName.GUESTBOOK.toLowerCase().indexOf(forum) != -1)
        {
            return TableName.GUESTBOOK;
        }
        else if (TableName.PICURL.toLowerCase().indexOf(forum) != -1)
        {
            return TableName.PICURL;
        }
        else if (TableName.FRIENDSITE.toLowerCase().indexOf(forum) != -1)
        {
            return TableName.FRIENDSITE;
        }
        return "";
    }
}
